package com.zerosoft.guotai.mqtt;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zerosoft.guotai.config.MqttProperties;
//import jakarta.annotation.Resource;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Component
public class MqttAcceptCallback implements MqttCallbackExtended {

    private static final Logger logger = LoggerFactory.getLogger(MqttAcceptCallback.class);

    @Resource
    private MqttAcceptClient    mqttAcceptClient;

    @Resource
    private MqttProperties mqttProperties;

//    @Resource
//    private SensorDataService sensorDataService;

    @Override
    public void connectComplete(boolean b, String s) {
        logger.info("============================= 客户端【" + MqttAcceptClient.client.getClientId() + "】连接成功！=============================");
        // 以/#结尾表示订阅所有以test开头的主题
        // 订阅所有机构主题
        mqttAcceptClient.subscribe(mqttProperties.getDefaultTopic(), 0);

    }

    @Override
    public void connectionLost(Throwable throwable) {
        logger.info("连接断开，可以重连");
        if (MqttAcceptClient.client == null || !MqttAcceptClient.client.isConnected()) {
            logger.info("【emqx重新连接】....................................................");
            mqttAcceptClient.reconnection();
        }
    }

    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        logger.info("【接收消息主题】:" + s);
        logger.info("【接收消息Qos】:" + mqttMessage.getQos());
        String msg = new String(mqttMessage.getPayload());
        logger.info("【接收消息内容】:" + msg);
        //        int i = 1/0;
        //TODO:保存到数据库，作用BLIOT格式
        //转换数据
        try{
            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonNode = mapper.readTree(msg);
//            List<SensorData> sensorDataList = new ArrayList<>();
//            if(jsonNode.has("gateway_indentify") && jsonNode.has("dev_info"))
//            {
//                String gateway = jsonNode.get("gateway_indentify").asText();
//                String device = jsonNode.get("dev_info").get("uart_dev_list").get(0).get("Dev_name").asText();
//                jsonNode.get("sensorDatas").forEach(dd -> {
////                SensorData sensorData1 = new SensorData();
////                sensorDataList.add(sensorData1);
////                System.out.println(dd);
////                System.out.println(dd.get("flag"));
////                System.out.println("gateway:"+gateway);
////                System.out.println("device:"+device);
//                    SensorData sensorData = new SensorData();
//                    sensorData.setGateway(gateway);
//                    sensorData.setDevice(device);
//                    sensorData.setSensor(dd.get("flag").asText());
//                    sensorData.setValue(dd.get("value").asInt());
//                    sensorData.setTimestamp(new Timestamp(System.currentTimeMillis()));
//                    System.out.println(sensorData);
//                    sensorDataList.add(sensorData);
//                });
//                sensorDataService.addSensorDatas(sensorDataList);
//            }
        }
        catch (Exception e)
        {
            logger.error("数据转换异常：{}",e.getMessage());
        }

    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        String[] topics = token.getTopics();
        for (String topic : topics) {
            logger.info("向主题【" + topic + "】发送消息成功！");
        }
        try {
            MqttMessage message = token.getMessage();
            byte[] payload = message.getPayload();
            String s = new String(payload, "UTF-8");
            logger.info("【消息内容】:" + s);
        } catch (Exception e) {
            logger.error("MqttAcceptCallback deliveryComplete error,message:{}", e.getMessage());
            e.printStackTrace();
        }
    }
}
